﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Xaml.Behaviors;

namespace NewChillers.Utils
{
    class HorizontalScrollBehavior : Behavior<ScrollViewer>
    {
        // 可以添加可配置属性
        public static readonly DependencyProperty ScrollSpeedProperty =
            DependencyProperty.Register(nameof(ScrollSpeed), typeof(double),
                typeof(HorizontalScrollBehavior), new PropertyMetadata(0.5));

        public double ScrollSpeed
        {
            get => (double)GetValue(ScrollSpeedProperty);
            set => SetValue(ScrollSpeedProperty, value);
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PreviewMouseWheel += OnPreviewMouseWheel;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PreviewMouseWheel -= OnPreviewMouseWheel;
        }

        private void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            var scrollViewer = AssociatedObject;
            if (scrollViewer != null && scrollViewer.IsEnabled)
            {
                double offset = scrollViewer.HorizontalOffset - (e.Delta * ScrollSpeed);

                // 确保不滚动超出范围
                offset = Math.Max(0, Math.Min(offset, scrollViewer.ScrollableWidth));

                scrollViewer.ScrollToHorizontalOffset(offset);
                e.Handled = true;
            }
        }
    }
}
